<template>
  <el-dialog title="提示"
             class="import-box"
             :visible="show"
             @closed="fileList = []"
             @update:visible="$emit('update:show', $event)">
    <div class="mb-20 tc">
      <a :href="demoUrl"><el-button type="primary">Excel模板文件</el-button></a>
      <el-button class="ml-10" type="primary" @click="$refs.file.click()">选择文件，批量上传</el-button>
      <input type="file" accept=".xls,.xlsx" style="display: none;" ref="file" @change="fileChange">
    </div>
    <div v-for="(item, index) in fileList" :key="item.lastModified" class="file-item fr ac p-5">
      <span class="f1">{{item.name}}</span>
      <span class="mr-20">{{item.size | filesize}}</span>
    </div>
    <!--<template #footer>-->
      <!--<el-button @click="$emit('update:show', false)">取 消</el-button>-->
      <!--<el-button type="primary" @click="submit">确 定</el-button>-->
    <!--</template>-->
  </el-dialog>
</template>

<script>
import axios from 'axios'

export default {
  name: 'import-box',
  props: {
    show: Boolean,
    demoUrl: String,
    url: String,
    params: Object
  },
  data () {
    return {
      fileList: []
    }
  },
  methods: {
    fileChange (e) {
      this.fileList.pop()
      this.fileList.push(e.target.files[0])
      e.target.value = null
      this.submit()
    },
    submit () {
      const { fileList, params, url } = this
      if (!fileList.length) {
        this.$notify.warning('请选择文件')
        return
      }
      const fd = new FormData()
      if (params) {
        for (const k in params) {
          fd.append(k, params[k])
        }
      }
      fd.append('file', fileList[0])
      axios.post(url, fd).then(
        res => {
          this.$notify.success(res.message || '导入成功')
          this.$emit('update:show', false)
        }
      )
    }
  }
}
</script>

<style lang="less">
.import-box .el-dialog {width: 400px;background-color: rgba(0, 112, 255, .2);border: 1px solid #0070ff;
  .el-dialog__header {text-align: center;}
  .el-dialog__title {color: #fff;font-weight: bold;}
  .el-dialog__close {color: #fff;}
  .el-dialog__body {color: #fff;}
  .el-button--primary {width: 170px;background-color: #202ab0;border-color: #202ab0;
    &:focus {background-color: #4d55c0;border-color: #4d55c0;}
    &:hover {background-color: #4d55c0;border-color: #4d55c0;}
    &:active {background-color: #1d269e;border-color: #1d269e;}
  }
  .file-item {border-radius: 5px;
    &:hover {background-color: rgba(255, 255, 255, .2);}
  }
}
</style>
